<template>
  <div style="padding:15px" v-loading="pageLoading">
    <div class="text-wrap flex flex-center flex-col-between">
      <div class="desc-text text-primary">
        <i class="el-icon-s-grid" />
        <span class="text">排程设备表格</span>
      </div>

      <div class="filter-container">
        <el-select class="filter-item" style="width: 260px;margin-left: 5px" v-model="query.ScheduleVersionId"
          placeholder="排程版本">
          <el-option v-for="i in VersionList" :key="i.value" :label="i.label" :value="i.value"></el-option>
        </el-select>
        <el-select @change="changePlant" class="filter-item" clearable style="width:200px;margin-right: 10px"
          v-model="plant" placeholder="选择工厂进行过滤">
          <el-option v-for="i in plantList" :key="i.value" :label="i.label" :value="i.value"></el-option>
        </el-select>
        <el-select class="filter-item" multiple @change="changeMachine" clearable style="width: 220px;margin-left: 5px"
          v-model="query.GroupId" placeholder="选择设备">
          <el-option v-for="i in MachineList" :key="i.value" :label="i.label" :value="i.value"></el-option>
        </el-select>

        <!-- <el-button class="filter-item" v-if="selectRows.length" type="danger" plain @click="research">删除
        </el-button> -->
        <el-button class="filter-item" type="success" plain @click="research">查询
        </el-button>
        <el-button class="filter-item" type="warning" plain @click="autoSchedule">重新生成排程版本
        </el-button>
        <el-button class="filter-item" type="primary" :loading='taskLoading' plain @click="openSaleOrder">任务下发
        </el-button>
        <el-button class="filter-item" type="warning" v-if="updateFlag" plain @click="updateCalculate">重新计算
        </el-button>
        <el-button class="filter-item" type="primary" v-if="updateFlag" plain @click="saveData">保存排程
        </el-button>
      </div>

    </div>
    <div class="custom-scrollbar" style="display: flex;flex-direction: column;" :style="{height:pageHeight+'px'}">
      <n-data-table :bordered="false" flex-height style="height: 100%" :scroll-x="scrollX"
        :scrollbar-props="scrollbarProps" :single-line="false" ref="table"
        :checked-row-keys="selectRows" @update:checked-row-keys="handleCheck" :columns="columns" :data="data">
        <template #loading>
          <div>数据疯狂加载中</div>
        </template>
      </n-data-table>
    </div>

    <el-dialog :title="`${curDate} 生产信息`" width="70%" v-model="dialogVisible">
      <z-Table :list="curMachineList" :tableProps="tableProps" :columns="columnsMachine">
        <template v-slot:content="{ row, key }">
          <span v-if="key == 'StartTime'" v-timeFormat="row[key]" format="HH:mm"></span>
          <span v-else-if="key == 'EndTime'" v-timeFormat="row[key]" format="HH:mm"></span>
          <span v-else> {{ row[key] }}</span>
        </template>

      </z-Table>
    </el-dialog>
    <el-dialog :title="`${curMo?.MoCode} 出货日修改`" v-model="ChangeDeadLine">
      <el-date-picker v-model="changeDeadLineValue" type="date" placeholder="选择日期" />
      <div class="fr">
        <el-button type="info" @click="ChangeDeadLine = false">取消</el-button>
        <el-button type="primary" @click="HandeChangeDeadLine">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="`订单任务下发`" v-model="saleOrderTaskFlag" width="50%">
      <div class="filter-container flex flex-center">
        <el-input style="width: 200px" placeholder="单号/物料名称模糊匹配" clearable @keyup.enter="openSaleOrder"
          @clear="openSaleOrder" v-model="taskQuery.query">
        </el-input>

      </div>
      <z-table :list="taskList" :tableProps="tablePropsTaskPatch" :columns="taskColumns" @editItem="editItem"
        @deleteItem="deleteItem" @row-click="rowClick">

        <template v-slot:operation="v">
          <div class="flex flex-row-sa">
            <a href="#" class="text-blue mr-10" @click.prevent="dispatchItem(v.row, v.$index)">下发任务</a>
          </div>
        </template>
      </z-table>
      <z-pagination :pagination="pagination" :total="taskTotal" v-model:page="taskQuery.page"
        v-model:limit="taskQuery.size" @change="openSaleOrder"></z-pagination>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, h, getCurrentInstance } from "vue";
import { useDraggable } from 'vue-draggable-plus'
import { NButton, NTag, useMessage, NConfigProvider } from "naive-ui";
import dayjs from 'dayjs'
import _ from 'lodash'
import zTable from '../../_common/table.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import commonMixin from '@/views/_common/mixin'

export default {
  components: { zTable },
  mixins: [commonMixin],
  data() {
    return {
      scrollX:null,
      pageHeight: document.documentElement.clientHeight-200,
      taskLoading: false,
      changeDeadLineValue: null,
      pageLoading:false,
      curDate: null,
      plantList:[],
      plant:null,
      curMo: null,
      curMachineList: [],
      scrollbarProps:{
        trigger:'none',
        size:20,
        "content-class":"content-class",
        "x-scrollable":true,
      },
      taskList:[],
      taskColumns:[
        { title: '订单编号', key: 'OrderNo', width: 200},
        { title: '订单产品', key: 'MaterialtName', width: 200 },
        { title: '订单交期', key: 'RequiredDate' },
        { title: '订单数量', key: 'TotalQty', width: 200 },
        // { title: '订单优先级', key: 'SalesOrderReq', width: 200 },
      ],
      taskTotal:0,
      taskQuery:{
        page:1,
        size:20,
        ids:[]
      },
      updateFlag:false,
      saleOrderTaskFlag:false,
      tableProps: {
        border: true,
        hideOperations: true,
      },
      tablePropsTaskPatch: {
        border: true,
        hideOperations: false,
      },
      CalculateTask:{},
      columnsMachine: [
        { title: '设备编码', key: 'MachineCode' },
        { title: '设备名称', key: 'MachineName' },
        // { title: '班次信息', key: 'ShiftType' },
        { title: '开始时间', key: 'StartTime' },
        { title: '结束时间', key: 'EndTime' },
        { title: '产出数量', key: 'Qty' },
        { title: '小时产能', key: 'UPH' },
        { title: '前置时长', key: 'BeforeMinutes' },
        { title: '准备时长', key: 'PreparationMinutes' },
        // { title: '后置时长', key: 'AfterMinutes' },

      ],
      ChangeDeadLine: false,
      dialogVisible: false,
      themeOverrides: {},
      query: {},
      VersionList: [],
      MachineList: [],
      selectRows: [],
      salarOrders:[],
      data: [
      ],

      BasColumns: [
        // {
        //   type: "selection",
        //   fixed: "left"
        // },
        {
          title: "设备",
          key: "GroupCodeName",
          width: 200,
          fixed: "left"
        },
        {
          title: "工单",
          key: "MoCode",
          width: 120,
          fixed: "left",
          render: null,
        },
        {
          title: "产品",
          key: "ProductsCode",
          width: 160,
          fixed: "left"
        },
        {
          title: "数量",
          key: "Qty",
          width: 80,
          fixed: "left"
        },
        {
          title: "UPH",
          key: "UPH",
          width: 80,
          fixed: "left"
        },
                {
          title: "出货日",
          key: "DeadLine",
          width: 100,
           fixed: "left",
          render: null,

        },
        // {
        //   title: "重量",
        //   key: "Weight",
        //   width: 80,
        //   // fixed: "left"
        // },


        // {
        //   title: "操作",
        //   key: "custom",
        //   width: 200,
        //   fixed: "right",
        //   render: null
        // }
      ],

      columns: [

      ],
    }


  },

  mounted() {
     this.init()
    this.getDictionary()
    let DeadLine = this.BasColumns.find(i => i.key == 'DeadLine')
    DeadLine.render = this.ageRender;
    this.themeOverrides = {
      common: {
        primaryColor: '#7606E6'
      },
      Button: {
        textColor: '#7606E6'
      },
      Select: {
        peers: {
          InternalSelection: {
            textColor: '#7606E6'
          }
        }
      }
    }
  },

  methods: {

    autoSchedule() {
      this.$confirm('确定要重新自动排程吗？', '提示',).then(r => {
        this.pageLoading = true
        this.http.get('api/Schedule/SyncAutoScheduling', {}).then(r => {
          // 当前页面重新加载
          this.http.post('/api/Aps_ScheduleVersion/GetPageData', { sort: "CreateTime" }).then(r => {
            this.VersionList = r.rows.map(i => {
              return {
                value: i.ScheduleVersionId,
                label: i.Version
              }
            })
            this.query.ScheduleVersionId = this.VersionList[0]?.value
            this.$message.success("重新排程成功")
            this.pageLoading = false

            this.research()
          })
        })
      })
    },
    openSaleOrder(){
      this.taskQuery.ids = [...this.salarOrders]
      this.http.post('/api/Aps_ScheduleTask/GetApsSalesOrderList', this.taskQuery).then(r => {
        this.taskList = r.rows
        this.saleOrderTaskFlag = true
        this.taskTotal = r.total
      })
    },
    dispatchItem(item, index) {
      this.taskInsert([item.SalesOrderId])
    },
    taskInsert(ids) {
      this.taskLoading = true

      this.http.post('/api/Aps_ScheduleTask/SendTask', { OrderIds:ids, ScheduleVersionId: this.query.ScheduleVersionId }).then(r => {
        this.saleOrderTaskFlag = false

      }).finally(i => {
        this.taskLoading = false

      })
    },

    titleRender(date, items) {
      return h("div", {
        style: 'color:orange',
        // onClick: (e) => this.handleTitleClick(date, items)
      }, date);
    },
    getDictionary() {
      this.http
        .post('api/Sys_Dictionary/GetVueDictionary', [
          "BASE_Plant"
        ]).then(r => {
          this.plantList = r[0].data.map(i => {
            return {
              value: i.key,
              label: i.value
            }
          })
          this.plant = (!!localStorage.getItem('Apsplant') && localStorage.getItem('Apsplant') != "undefined")? Number(localStorage.getItem('Apsplant')) : null
        })
    },
    handleTitleClick(date, items) {

      this.curDate = date
      this.curMachineList = items
      this.dialogVisible = true
    },
    changeMachine(){
      this.plant = null
      this.research()
      
    },
    changePlant() {
      localStorage.setItem('Apsplant', this.plant) // 将工厂缓存起来
      this.research()
    },
    research() {
      this.pageLoading = true
      let data = {
        ...this.query,
        MachineIds: this.query.GroupId?.length ? this.query.GroupId : this.MachineList.map(i => i.value),
        // MachineIds: this.MachineList.map(i => i.value),
        PlantId:this.plant
      }
      this.http.post('/api/Aps_ScheduleTask/GetGanttChartDataByMachine', data).then(r => {
        this.renderData(r)
      }).finally(i => {
        this.pageLoading = false
      })
    },
    saveData(){
      this.http.post('/api/Schedule/SaveSchedule', { ...this.CalculateTask }).then(r => {
        this.research()
        this.updateFlag = false

        thi.CalculateTask = {}
      })
    },
    updateCalculate(){
      // if (this.data.some(i => i.Status != 0)) {
      //   return this.$message.error('只能计算待执行状态的数据')
      // }
      this.http.post('/api/Schedule/HandDeviceSchedule', { TaskList:this.data}).then(r => {
        this.renderData(r)
        this.CalculateTask = {
          reqTask:r.tasks,
          reqDate: r.taskDates
        }
      })
    },
    // 造数据
    renderData(r) {
      this.pageLoading = true
      this.selectRows = []

      let that = this
      const { MinDate, MaxDate, task, taskDate } = r
      // 循环MinData到MaxData 时间
      let minDate = dayjs(MinDate)
      this.minDateStr = minDate.format('YYYY-MM-DD')
      let maxDate = dayjs(MaxDate).add(1, 'day')
      this.columns = _.cloneDeep(this.BasColumns)
      this.data = task.map(i => {
        return {
          ...i,
          key: i.ScheduleTaskId
        }
      })
      // 循环时间，工单当天qty值多少显示在表格中
      for (let i = minDate; i.isBefore(maxDate); i = i.add(1, 'day')) {
        let date = i.format('YYYY-MM-DD')

        this.data.forEach((j, index) => {
          let tmp = taskDate.find(x => x.MoCode == j.MoCode && dayjs(x.WorkDate).format('YYYY-MM-DD') == date)
          if (!!tmp ) {
            //处理展示数据 找到对应的工序，工单，产品，给对应需要展示的数据塞入值
            if (tmp.GroupId == j.MachineId  && tmp.ProductsCode == j.ProductsCode) {
              this.data[index][date] = tmp.Qty
              this.data[index][date+'detail'] = tmp.Details
            } else {
              this.data[index][date] = null
              this.data[index]['detail'] = []

            }
          } else {
            this.data[index][date] = null
            this.data[index]['detail'] = []

          }

          // 处理columns
          if(!this.columns.filter(i => i.curDate == date).length ) {
            this.columns.push({
              title: this.titleRender(date, this.data[index][date+'detail']),
              key: date,
              width: 90,
              curDate:date,
              render(row) {
                return h("div", {
                  style: 'color:green;cursor: pointer;font-weight:700',
                  onClick: (e) => that.handleTitleClick(date, row[date+'detail'] ?? [])
                }, row[date]);
              },
              fixed: false,
              only: true,
            })
          }
          


        })

      }
      // this.columns.push({
      //   title: "操作",
      //   key: "custom",
      //   width: 100,
      //   fixed: "right",
      //   render: null
      // })
      this.$nextTick(() => {
        this.scrollX = this.columns.length * 0
        this.pageLoading = false

        let list = this.data.map(i => i.SalesOrderId)
        // 对list去重
        this.salarOrders = new Set(list)

        this.data = this.data.concat(this.data).concat(this.data)

      })
    },
    sendMail() { },
    init() {
      this.http.post('/api/Aps_ScheduleVersion/GetPageData', { sort: "CreateTime" }).then(r => {
        this.VersionList = r.rows.map(i => {
          return {
            value: i.ScheduleVersionId,
            label: i.Version
          }
        })
        this.query.ScheduleVersionId = this.VersionList[0]?.value
        this.http.post('/api/Bas_Machine/GetPageData', { sort: "Level",rows:999}).then(r => {
         r.rows = r.rows.filter(i => i.Level != null)
          this.MachineList = r.rows.map(i => {
            return {
              value: i.MachineId,
              label: `${i.MachineCode} ${i.MachineName}`,
              code: `${i.MachineCode} `
            }
          })
          this.MachineList = this.MachineList.sort((a, b) => a.code - b.code > 0 ? 1 : -1)
          this.research()

        })
      })

    },
    handleCheck(items) {
      this.selectRows = items
      // this.selectRows = [items[items.length-1]] // 只能选一个
      let custom = this.columns.find(i => i.key == 'custom')
      if (items.length) {
        custom.render = this.customRender;
      } else {
        custom.render = null;
      }

    },
    ageRender(row, index) {
      return h("div", {
        style: 'color:red;cursor: pointer;',
        //onClick: (e) => this.handleAgeClick(row, index, e)
      }, dayjs(row.DeadLine).format('YYYY-MM-DD'));
    },
    moveElements(ids, targetId) {
      const targetIndex = this.data.findIndex(item => item.key === targetId);

      const elementsToMove = [];
      ids.forEach(key => {
        const index = this.data.findIndex(item => item.key === key);
        if (index !== -1) {
          elementsToMove.push(this.data.splice(index, 1)[0]);
        }
      });

      elementsToMove.forEach(element => {
        this.data.splice(targetIndex + 1, 0, element);
      });
    },
    moveTop(row, index) {
      if (this.query.ScheduleVersionId != this.VersionList[0]?.value) {
        this.$message.info("只能拖拽最新的排程版本")
        return
      }
      let curSelect = this.data.filter(i => this.selectRows.includes(i.key))
      this.data = this.data.filter(i => !this.selectRows.includes(i.key))
      let cIndex = this.data.findIndex(i => i.key == row.key)
      this.data.splice(cIndex, 0, ...curSelect)
      this.updateFlag = true
    },
    moveBottom(row, index) {
      if (this.query.ScheduleVersionId != this.VersionList[0]?.value) {
        this.$message.info("只能拖拽最新的排程版本")
        return
      }
      let curSelect = this.data.filter(i => this.selectRows.includes(i.key))
      this.data = this.data.filter(i => !this.selectRows.includes(i.key))
      let cIndex = this.data.findIndex(i => i.key == row.key)
      this.data.splice(cIndex + 1, 0, ...curSelect)
      this.updateFlag = true
    
    },
    customRender(row, index) {
      if (!this.selectRows.length || this.selectRows.includes(row.key)) {
        return null
      }
      return h(
        'div',
        {},
        [
          h(
            NButton,
            {
              size: 'small',
              style: { marginRight: '10px' },
              onClick: () => this.moveTop(row, index),
            },
            { default: () => '向上' }
          ),
          h(
            NButton,
            {
              size: 'small',
              onClick: () => this.moveBottom(row, index),
            },
            { default: () => '向下' }
          ),
        ]
      );
    },
    HandeChangeDeadLine() {
      this.ChangeDeadLine = false
      // TODO 接口
      console.log("🚀 ~ HandeChangeDeadLine ~ this.curMo:", this.curMo)
    },
    handleAgeClick(row, index, e) {
      this.curMo = row
      this.changeDeadLineValue = row.DeadLine
      this.ChangeDeadLine = true
    },
    rowProps: (row, index, item) => {
      const { proxy } = getCurrentInstance();

      return {
        style: "cursor: pointer;",
        onClick: () => {
          console.log(row, index, item, 'proxy')
          proxy.$message.info(row)
        }
      };
    },
    initSortable: function () {
      // 获取表格row的父节点
      const ele = this.$refs.table.$refs.mainTableInstRef.$el.querySelector(".n-data-table-tbody")
      this.$nextTick(() => {
        useDraggable(ele, this.data)
      })
    },
    getData() {
      console.log("🚀 ~ getData ~ this.data:", this.data)
    },
  },
}
</script>

<style lang="scss" scoped>

.text-wrap {
  height: 40px;
  position: relative;
  padding-bottom: 8px;
  display: flex;

  .desc-text {
    //  display: inline-block;
    margin-top: 7px;
    font-weight: bold;
    //margin-bottom: 3px;
    font-size: 14px;
    white-space: nowrap;
    border-bottom: 2px solid #7300e6;

    i {
      font-size: 16px;
      position: relative;
      top: 1px;
      margin-right: 2px;
    }
  }
}
.content-class {
  width: 10px;
  height: 10px;
}
::v-deep .n-scrollbar-rail--vertical--right>.n-scrollbar-rail__scrollbar {
  background-color: #b9b9b9a7 !important;
  width: 35px !important;
}
::v-deep .n-scrollbar-rail--horizontal--bottom >.n-scrollbar-rail__scrollbar {
  background-color: #b9b9b9a7 !important;
  height:35px !important;
}
.text-blue {
  color:#7606E6;
  font-weight: 500;
}
</style>
